package com.okoj.excel_lib_rary;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.okoj.excel_lib_rary.config.Config;
import com.okoj.excel_lib_rary.ui.TemplateListActivity;
import com.okoj.excel_lib_rary.util.SDCardUtils;
import com.okoj.excel_lib_rary.util.WpsHelper;
import com.okoj.excel_lib_rary.util.WpsInitUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class TestActivity extends AppCompatActivity {

    private static String TAG = TestActivity.class.getName();

    public static final int CHOOSE_FILE_CODE = 0x43;
    private String tempUserToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDIwMDYzNiwiZXhwIjoxNjI0NTQ2NDE3LCJzY29wZSI6IkdlbmVyYWxTY29wZSJ9.A0jasbCQhI6yPrBT2hr8FNNDODSkB5_mKpyAk8U4eTo";
    private String temUserId = "4200636";
    private String appid = "ANDROID_EXCEL_FOUR";
    private int env  = 2; /* 1正式，2测试 */


    /**
     * 权限组
     */
    private static final String[] permissionsGroup = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wps_activity_test);

        initWps();


        findViewById(R.id.btn_new).setOnClickListener(view -> {
            WpsHelper.creteForm(this);
        });

        findViewById(R.id.file_list).setOnClickListener(view -> {
            WpsHelper.showRemoteFile(this);
        });

        findViewById(R.id.btn_edit).setOnClickListener(view -> {
            chooseFile();
        });

        findViewById(R.id.btn_new_word).setOnClickListener(v -> {
            WpsHelper.creteWord(this);
        });

        findViewById(R.id.btn_new_ppt).setOnClickListener(v -> {
            WpsHelper.cretePPT(this);
        });

        findViewById(R.id.template_list).setOnClickListener(v -> {
            TemplateListActivity.showTemplate(this);
        });


        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissionsGroup)

                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if(aBoolean){

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initWps() {
        // 初始化
        Config config = new Config();
        config.setToken(tempUserToken);
        config.setUserId(temUserId);
        config.setAppid(appid);
        config.set_w_env(env);
        config.set_w_platform(1);
        // 确保文件夹已经创建
        File saveDir = new File(SDCardUtils.getSDCardPath(),"wpsOffice") ;
        if(!saveDir.exists() || !saveDir.isDirectory()){
            saveDir.mkdirs();
        }
        config.setDownloadPath(saveDir.getAbsolutePath());
        WpsInitUtil.init(config,this);
    }


    // 调用系统文件管理器
    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Choose File"), CHOOSE_FILE_CODE);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "亲，木有文件管理器啊-_-!!", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    // 文件选择完之后，自动调用此函数
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CHOOSE_FILE_CODE) {
                Uri uri = data.getData();
                String filePath = getFilePathForN(uri,this);
                WpsHelper.openLocalFile(this,filePath);
            }
        } else {
            Log.e(TAG, "onActivityResult() error, resultCode: " + resultCode);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    public static String getFilePathForN(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getFilesDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }
}